import { Pipe, PipeTransform } from '@angular/core';
import { toNumber } from '@delon/util';

const MAX_SAFE_INTEGER = 9007199254740991;
const MAX_ARRAY_LENGTH = 4294967295;

/**
 * 循环次数
 */
@Pipe({
  name: 'times'
})
export class TimesPipe implements PipeTransform {
  /**
   * 枚举
   * @param value
   * @param args
   */
  transform(value: any, args?: (index: number) => void): any {
    value = toNumber(value);
    if (value < 1 || value > MAX_SAFE_INTEGER) {
      return [];
    }
    const length = Math.min(value, MAX_ARRAY_LENGTH);

    if (typeof args !== 'function') {
      args = x => {
        x;
      };
    }
    return baseTimes(length, args);
  }
}

function baseTimes(n: number, fn: (x: number) => void): any[] {
  let index = -1;
  const result = Array(n);
  while (++index < n) {
    result[index] = fn(index);
  }
  return result;
}
